<?php
class App_IndexController extends Zendvn_Controller_Action{
	
	public  function init(){
		
		//check login cookie
		
		$user = new Registration_Model_Auth();
		
		if($user->checkLoginCookie() == false){
			
			$this->_redirect("/registration/auth/login/");
		}
		
		if($user->checkLoginCookieToken() == false){
			
			$this->_redirect("/integrate/");
			
		}
		
		
		$this->createTemplate(APPLICATION_PATH . '/templates/dashboard','template.ini','template');
	}
	
	public function indexAction(){
		
			$user = Cu_Facebook::getUser();
	
			if ($user) {
				
			     try {
			     	
			     	$storage = new Zend_Auth_Storage_Session();
					$data = $storage->read();
								     	
			     	$shop = new Shop_Model_Index();
			     	$arr = array(
			     		"userid"=> $data->id,
			     	);
					$list_shop = $shop->listItem($arr);	

					if($list_shop){
						$this->view->list_shop = $list_shop;
					}else{
						
						// Insert Shop
					
						$accounts = Cu_Facebook::api('/me/accounts');
        						    
        				foreach($this->accounts['data'] as $account){
        					
        					$arr = array(
			                	"name"=>$account["name"],
			                	"pageid"=>$$account["id"],
			                	"userid"=>$data->id,               	
			                	
	                		);
	                		$shop->insertShop($arr);        					
        				}
        				
        				$this->view->list_shop = $shop->listItem($arr);
        				
					}
					
        			
			    } catch (FacebookApiException $e) {
			        echo $e->getMessage();
			    }
			}
	}
	
	
	
	public function uploadphotoAction(){
		
		
		// Get User ID
		$user = Cu_Facebook::getUser();
		
		if ($user) {
		
			$this->createTemplate(APPLICATION_PATH . '/templates/ajax','template.ini','template');
			
			$upload = new Zend_File_Transfer_Adapter_Http();
										
			$path = realpath(APPLICATION_PATH."/../photo/");
			
			$upload->setDestination($path);
			
			 $file = $upload->getFileInfo();
			 
			  $file_name = $upload->getFilename();
			  
			  preg_match("/\.([^\.]+)$/", $file_name, $matches); 
		          $file_ext = $matches[1];
		          $file_name = (string)$user.time() . '.' . $file_ext;
		          $upload->addFilter('Rename', $path .'/' . $file_name);
			
			if (!$upload->isValid()) 
			{
			    throw new Exception('Bad image data: '.implode(',', $upload->getMessages()));
			}
			
			try {
				
			        $upload->receive();
			        
			        echo $file_name;
					
					
				// Send photo to Facebook
						
				     try {
	
				     	$fanpage = @$_GET["page"];
				     	
				     	if($fanpage != ""){
	
				     		$access_token = Cu_Facebook::getAccessToken();
				     	
		        			$accounts = Cu_Facebook::api('/me/accounts');
		        			
						    foreach($accounts['data'] as $account) {
			 					if( $account['id'] == $fanpage || $account['name'] == $fanpage ){
			  						$fanpage_token = $account['access_token'];
			  						
			 					}
							}
		        			
							// allow uploads
							Cu_Facebook::setFileUploadSupport("http://" . $_SERVER['SERVER_NAME']);
							
							//insert product
		    				$product = new Shop_Model_Product();
		    				$arr = array(
		    					"detail"=>@$_GET["detail"],
		    					"shopid"=>@$_GET["shopid"],
		    					"image"=>$file_name,
		    					"sku"=>"",
		    					"stock"=>"",		    					
		    				);
		    				$idproduct = $product->insertProduct($arr);
							
							$str =  @$_GET["des"]."\n Click mua ngay tại >>> http://apps.facebook.com/thietdep/?product=".$idproduct;
		
							$des = $this->makeLinks($str);
		
							$fb_pfoto = Cu_Facebook::api('/' . $fanpage . '/photos','POST',array(									
			      							'access_token' => $fanpage_token,
		       								'message'      => $des,								
			      							'source'       => '@' . realpath(APPLICATION_PATH ."/../photo/".$file_name)
		
		
		    				));
		    									     		
				     	}			     	
	        			
				    } catch (FacebookApiException $e) {
				        echo $e->getMessage();
				    }
					
				}	
		 
				catch (Zend_File_Transfer_Exception $e) 
				{
				        throw new Exception('Bad image data: '.$e->getMessage());
				}
		}
		
				
	}
	
	function makeLinks($str) {
		
		$bitly = new Bitly_Bitly();
		
		$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
		$urls = array();
		$urlsToReplace = array();
		if(preg_match_all($reg_exUrl, $str, $urls)) {
			$numOfMatches = count($urls[0]);
			$numOfUrlsToReplace = 0;
			for($i=0; $i<$numOfMatches; $i++) {
				$alreadyAdded = false;
				$numOfUrlsToReplace = count($urlsToReplace);
				for($j=0; $j<$numOfUrlsToReplace; $j++) {
					if($urlsToReplace[$j] == $urls[0][$i]) {
						$alreadyAdded = true;
					}
				}
				if(!$alreadyAdded) {
					array_push($urlsToReplace, $urls[0][$i]);
				}
			}
			
			$numOfUrlsToReplace = count($urlsToReplace);
			for($i=0; $i<$numOfUrlsToReplace; $i++) {
				$str = str_replace($urlsToReplace[$i],$bitly->get_bitly_short_url($urlsToReplace[$i],"txt"), $str);
			}
			return $str;
		} else {
			return $str;
		}
	}
	
}